Page({

  data: {  
    // 文本框的数据模型
    input: '',
    // 任务清单数据模型
    todos: [
      { name: 'Learning WEAPP', completed: false },
      { name: 'Learning JavaScript', completed: true },
      { name: 'Learning HTML', completed: false }
    ],
    leftCount: 2,
    allCompleted: false
  },
  //拿到文本框里边的值
  // 小程序的数据绑定是单向的 必须要给文本框绑定事件
  inputChangeHandle(e){
    console.log(e)
    this.setData({ input : e.detail.value})
  },
  //点击事件触发回调函数  对todos数组添加数据
  addToHandle(){
    if (!this.data.input) {
      return
    }
    var todos = this.data.todos;
    todos.push({
      name : this.data.input,
      completed : false
    })

    //必须通过setData()去显示的改变  界面才会发生变化
    this.setData({
      todos:todos,
      input : '',
      leftCount:this.data.leftCount+1
    })
  },

  toggleTodoHandle(e){
    //切换当前选中的item的完成状态
    // console.log(e.currentTarget)
    var item = this.data.todos[e.currentTarget.dataset.index]
    // console.log(item)
    item.completed = !item.completed;
    //根据当前任务的完成状态 决定是+还是-
    var leftCount = this.data.leftCount + (item.completed?-1:1)
    this.setData({
      todos:this.data.todos,
      leftCount:leftCount
    })

  },
  removeTodoHandle(e){
    //注意冒泡的问题
    var todos = this.data.todos;
    //item就是splice方法中移除的元素
    var item = todos.splice(e.currentTarget.dataset.index,1)[0]
    // console.log(item)
    // console.log(todos)
    //todos会移除掉index所指向的元素
    var leftCount = this.data.leftCount - (item.completed?0:1)
    this.setData({
      todos:todos,
      leftCount:leftCount
    })
  },

  toggleAllHandle(){
    //this在这里永远指向的是当前页面对象
    this.data.allCompleted = !this.data.allCompleted;
    var todos = this.data.todos;
    var that = this
    todos.forEach(function(item){
      item.completed = that.data.allCompleted
    })

    var leftCount = this.data.allCompleted?0:this.data.todos.length

    this.setData({
      todos:todos,
      leftCount:leftCount
    })

  },

  clearHandle(){

    var todos = []

    this.data.todos.forEach((item)=>{
      if (!item.completed) {
        todos.push(item)
      }
    })

    // var todos = this.data.todos.filter(function(item){
    //   return !item.completed
    // })
    this.setData({
      todos:todos
    })
  }








})
